package com.lei.emos.wx.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lei.emos.wx.db.dao.TbUserDao;
import com.lei.emos.wx.exception.EmosException;
import com.lei.emos.wx.service.UserService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.support.ManagedMap;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Set;

@Service
@Slf4j
@Scope("prototype")
public class UserServiceImpl implements UserService {
    @Value("${wx.app-id}")
    private String appId;

    @Value("${wx.app-secret}")
    private String appSecret;

    @Autowired
    private TbUserDao userDao;

    /**
     * 获取openid
     * @param code 传过来得临时授权码
     * @return
     */
    private String getOpenId(String code){
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        HashMap map = new ManagedMap();
        map.put("appid",appId);
        map.put("secret",appSecret);
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String response = HttpUtil.post(url, map);
        JSONObject json = JSONUtil.parseObj(response);
        String openId = json.getStr("openid");
        if (openId==null||openId.length()==0){
            throw new RuntimeException("临时登录凭证错误");
        }
        return openId;
    }

    /**
     *  注册
     * @param registerCode 注册码
     * @param code 临时授权码
     * @param nickName 用户名
     * @param photo 头像
     * @return
     */
    @Override
    public int registerUser(String registerCode, String code, String nickName, String photo) {
       //6个0 为超级管理员注册码
        if (registerCode.equals("000000")){
            //判断是否存在超级管理员
           boolean b = userDao.haveRootUser();
           if (!b){
               String openId = getOpenId(code);
               HashMap param = new HashMap();
               param.put("openId",openId);
               param.put("nickname",nickName);
               param.put("photo",photo);
               param.put("role","[0]");
               param.put("status",1);
               param.put("createTime",new Date());
               param.put("root",true);
               userDao.insert(param);
               Integer id = userDao.searchIdByOpenId(openId);
               return id;
           }
           //存在超级管理员 禁止注册
            else {
                throw new EmosException("无法绑定超级管理员账号");
           }
       }else {

        }

        return 0;
    }

    /**
     * 获取角色权限
     * @param userId
     * @return
     */
    @Override
    public Set<String> searchUserPermissions(int userId) {
        Set<String> permissions = userDao.searchUserPermissions(userId);
        return permissions;
    }

    /**
     * 登录方法 openId判断
     * @param code
     * @return
     */
    @Override
    public Integer login(String code) {
        //临时收取码 获取openId
        String openId = getOpenId(code);
        Integer id = userDao.searchIdByOpenId(openId);
        if (id==null){
            throw new EmosException("账户不存在");
        }
        //TODO 从消息队列中接受消息，转移到消息列表
        return id;
    }
}
